package wicketcool;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import wicketcool.converter.ClassModelCompilationUnitConverter;
import wicketcool.converter.InterfaceModelCompilationUnitConverter;
import wicketcool.model.WCLClass;
import wicketcool.model.WCLInterface;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * User: rabbit
 * Date: Jul 28, 2009
 */
@Component
public class DefaultJavaClassGenerator implements JavaClassGenerator {

    @Autowired
    private ClassModelCompilationUnitConverter classConverter;

    @Autowired
    private InterfaceModelCompilationUnitConverter interfaceConverter;

    public WCLClass initClass(String className, String packageName) {
        return new WCLClass(className, packageName);
    }

    public WCLInterface initInterface(String className, String packageName) {
        return new WCLInterface(className, packageName);
    }

    public File createFileFromClass(WCLClass model, String path) {
        return createFile(model.getName(), path, classConverter.classToCompilationUnit(model).toString());
    }

    public File createFileFromInterface(WCLInterface model, String path) {
        return createFile(model.getName(), path, interfaceConverter.interfaceToCompilationUnit(model).toString());
    }

    private File createFile(String name, String path, String content) {
        File file = new File(path + File.separator + name + ".java");
        try {
            file.createNewFile();
            PrintWriter pw = new PrintWriter(new FileWriter(file));
            pw.write(content);
            pw.flush();
            pw.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }
}
